import jieba
from typing import Dict, List, Tuple

# 定义常量
NAMES = ["曹操", "刘备", "诸葛亮", "孙权", "周瑜"]
FILE_PATH = "python-project/static/三国演义.txt"

def count_names_in_text(text: str, names: List[str]) -> Dict[str, int]:
    """统计文本中指定人名的出现次数"""
    words = jieba.cut(text)
    word_counts = {}
    for word in words:
        if word in names:
            word_counts[word] = word_counts.get(word, 0) + 1
    return word_counts

def main():
    try:
        with open(FILE_PATH, "r", encoding="utf-8") as f:
            text = f.read()
        
        word_counts = count_names_in_text(text, NAMES)
        sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)

        for word, count in sorted_word_counts:
            print(f"{word}: {count}")
            
    except FileNotFoundError:
        print(f"错误：文件 {FILE_PATH} 未找到")
    except Exception as e:
        print(f"发生错误：{str(e)}")

if __name__ == "__main__":
    main()
